/**
 *  Project: CloudstickUtils 
 *  kr.cloudstick.util-CSTime.java
 * 	
 *	Copyright 2013 Cloudstick (www.cloudstick.kr)
 *
 *	Written by htkim
 *		2013. 3. 25. first written.
 *
 *	Note:	
 */
package kr.cloudstick.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

public final class CSTime {
	
	private CSTime() {
		throw new AssertionError();
	}
	
	public static long getTimeTicks() {
		return System.currentTimeMillis();
	}
	
	public static long getTimeElapsed(final long ticks) {
		return getTimeTicks() - ticks;
	}
	
	public static long getTimeDiff(final long ticks1, final long ticks2) {
		return ticks1 >= ticks2 ? ticks1 - ticks2 : ticks2 - ticks1;
	}
	
	public static boolean containTime(final long start, final long end, final long ticks) {
		return start <= ticks && end >= ticks;
	}
	
	public static String getFormattedDate(final String format, final long ticks) {
		try {
			final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.KOREA);
			return simpleDateFormat.format(new java.util.Date(ticks)).toString();
		} catch (IllegalArgumentException e) {
			throw new CSException("Invalid date format[" + format + "]", e);
		}
	}
	
	public static String getFormattedDateNow(final String format) {
		return getFormattedDate(format, getTimeTicks());
	}
	
	public static long getTicksFromFormattedDate(final String format, final String formattedDate) {
		try {
			final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.KOREA);
			return simpleDateFormat.parse(formattedDate).getTime();
		} catch (ParseException e) {
			throw new CSException("Failed to parse formattedDate[" + formattedDate + "]", e);
		} catch (IllegalArgumentException e) {
			throw new CSException("Invalid date format[" + format + "]", e);
		}
	}
}